import * as mongodb from 'mongodb'
const Db_Name = 'metronic'
const Record_Sync_Table: string = "InspectSyncRecord";
const Mongo_Url = 'mongodb://localhost:27017';
const Line_Sync_Table = 'InspectLine';

interface ISyncRecord {
    name: string, date: string, section: string, sectionName?: string
}

/** 这个记录是否已经同步过 */
export async function isRecordSyncAlready(db: mongodb.Db, record: ISyncRecord): Promise<boolean> {
    let collection = db.collection(Record_Sync_Table);
    let res = await collection.findOne({ name: record.name, date: record.date, sectionName: record.section })
    return !!res;
}

/** 将存的结果同步到mongo里去 */
export async function saveSyncRecord(db: mongodb.Db, record: ISyncRecord) {
    let collection = db.collection(Record_Sync_Table);
    let res = await collection.insertOne(record);
}

/** 打开一个对mongodb的访问 */
export async function openMongoAsync() {
    let client = await mongodb.connect(Mongo_Url)
    let db = client.db(Db_Name)
    return { client, db };
}

/** 关闭数据访问 */
export async function closeMongoAsync(client: mongodb.Db) {
    await client.close()
}

/** 根据线路的名称获取线路数据 */
export async function getLineByNameAsync(db: mongodb.Db, lineName: string) {
    let collection = db.collection(Line_Sync_Table);
    let line = await collection.findOne({ name: lineName })
    return line
}

/** 直接更新数据库中的line
 * 颗粒度比较粗糙！！！ 呵呵
 */
export async function updateLineAysnc(db: mongodb.Db, lineName: string, newLine) {
    let collection = db.collection(Line_Sync_Table);
    let line = await collection.findOne({ name: lineName })
    if (!line) {//不存在就insert
        await collection.insertOne(newLine)
    } else {//存在就update
        await collection.findOneAndUpdate({ name: lineName }, newLine)
    }
}